import ReconnectingWebSocket from 'reconnecting-websocket';

export function useWebSocket() {
  let socket = null;
  const listeners = {};
  
  const connect = (phone) => {
    if (socket) {
      disconnect();
    }

// 修正后的WebSocket连接地址
    const wsUrl = `ws://localhost:8066/ws/code`;
    socket = new ReconnectingWebSocket(wsUrl, [], {
      connectionTimeout: 5000,
      maxRetries: 10,
      debug: false,
    });

    socket.onopen = () => {
      console.log('WebSocket连接已建立');
    };

    socket.onmessage = (event) => {
      const code = event.data;
      console.log('收到验证码:', code);
      if (listeners['code']) {
        listeners['code'].forEach(callback => callback(code));
      }
    };

    socket.onerror = (error) => {
      console.error('WebSocket错误:', error);
    };

    socket.onclose = () => {
      console.log('WebSocket连接已关闭');
    };
  };

  const disconnect = () => {
    if (socket) {
      socket.close();
      socket = null;
    }
  };

  const on = (event, callback) => {
    if (!listeners[event]) {
      listeners[event] = [];
    }
    listeners[event].push(callback);
  };

  const off = (event, callback) => {
    if (listeners[event]) {
      listeners[event] = listeners[event].filter(
        (listener) => listener !== callback
      );
    }
  };

  return {
    connect,
    disconnect,
    on,
    off
  };
}